<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高德地图路径规划</title>
    <style>
        body { margin: 0; padding: 20px; font-family: Arial, sans-serif; }
        .container { max-width: 1200px; margin: 0 auto; }
        .search-box { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
        .input-group { position: relative; flex: 1; min-width: 250px; }
        input { width: 100%; padding: 10px 15px; border: 1px solid #ccc; border-radius: 4px; font-size: 16px; box-sizing: border-box; }
        button { margin-left: 25px; background-color: #38f; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }
        button:hover { background-color: #27e; }
        button:disabled { background-color: #999; cursor: not-allowed; }
        #map { width: 100%; height: 600px; border: 1px solid #ccc; border-radius: 4px; }
        .suggestion-box { position: absolute; top: 100%; left: 0; right: 0; background: white; border: 1px solid #ccc; border-top: none; border-radius: 0 0 4px 4px; max-height: 200px; overflow-y: auto; z-index: 1000; display: none; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        .suggestion-item { padding: 10px 15px; cursor: pointer; border-bottom: 1px solid #f0f0f0; font-size: 14px; }
        .suggestion-item:last-child { border-bottom: none; }
        .suggestion-item:hover { background-color: #f5f5f5; }
        .suggestion-item.selected { background-color: #e6f7ff; color: #1890ff; }
        .suggestion-item .name { font-weight: 500; color: #333; }
        .suggestion-item .address { font-size: 12px; color: #999; margin-top: 2px; }
        .result-info { margin-top: 15px; padding: 10px; border: 1px solid #eee; border-radius: 4px; }
        .error-message { color: #f00; margin-top: 10px; }
        .loading { color: #666; margin-top: 10px; display: none; }
        .route-detail { margin-top: 10px; padding-left: 20px; line-height: 1.6; }
        .debug-info { margin-top: 10px; padding: 10px; background: #f9f9f9; border-radius: 4px; font-size: 14px; color: #666; }
        .api-key-box { margin-bottom: 20px; }
        .required::after { content: " *"; color: red; }
        
        /* 新增的布局样式 */
        .map-container {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        .map-content {
            flex: 3;
        }
        .info-content {
            flex: 1;
            min-width: 300px;
            height: 600px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>高德地图路径规划</h1>
        <div class="api-key-box">
            <div class="input-group">
                <input type="text" id="apiKey" value="33b277122a5723576635b52523078762" placeholder="请输入高德地图API Key（必填）">
            </div>
        </div>
        <div class="search-box">
            <div class="input-group">
                <input type="text" id="startPoint" placeholder="请输入起点（例如：北京天安门）">
                <div class="suggestion-box" id="startSuggestion"></div>
            </div>
            <div class="input-group">
                <input type="text" id="endPoint" placeholder="请输入终点（例如：北京颐和园）">
                <div class="suggestion-box" id="endSuggestion"></div>
            </div>
            <button id="searchBtn">查询路线</button>
        </div>
        
        <!-- 路线偏好 -->
        <div class="options-box" style="display: flex; gap: 20px; margin-bottom: 20px; flex-wrap: wrap;">
            <div class="route-preference">
                <label style="margin-right: 10px;">路线偏好：</label>
                <select id="routePreference" style="padding: 8px; border: 1px solid #ccc; border-radius: 4px;">
                    <option value="0">默认</option>
                    <option value="35">不走高速</option>
                    <option value="34">高速优先</option>
                    <option value="33">躲避拥堵</option>
                    <option value="36">少收费</option>
                    <option value="38">时间优先</option>
                </select>
            </div>
            <div class="cost-box" style="display: flex; gap: 10px;">
                <input type="number" id="unitPriceInput" placeholder="请输入单价（元/公里）" style="width: 180px; padding: 8px; border: 1px solid #ccc; border-radius: 4px;">
                <button id="calcCostBtn">计算费用</button>
            </div>
        </div>
        
        <!-- 地图和信息容器 -->
        <div class="map-container">
            <div class="map-content">
                <div id="map"></div>
            </div>
            <div class="info-content">
                <div class="loading" id="loading">正在规划路线，请稍候...</div>
                <div class="error-message" id="errorMsg"></div>
                <div class="result-info" id="costInfo"></div>
                <div class="result-info" id="routeInfo"></div>
                <div class="debug-info" id="debugInfo">调试信息：</div>
            </div>
        </div>
    </div>

    <script type="text/javascript">
        window._AMapSecurityConfig = {
            securityJsCode: "396c4a78083e31cafd8de6210dc66a2b",
        };
    </script>
    <!-- 高德地图API（请替换为自己的AK） -->
    <script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=bbde4502edad0a5e0e7e2864d2c3fa6f"></script>
    
    <script>
        // 页面加载完成后的初始化
        window.addEventListener('load', function() {
            // 检查API加载状态
            if (typeof AMap === 'undefined') {
                document.getElementById('errorMsg').textContent = "高德地图API加载失败，请检查网络连接或API Key配置";
                console.error("高德地图API加载失败，请检查网络连接或API Key配置");
                return;
            }
            
            // 初始化地图（中心点设为北京，可根据需求修改）
            const map = new AMap.Map("map", {
                zoom: 12,
                center: [116.404, 39.915]
            });
            
            // 将map对象存储到全局变量中，供其他函数使用
            window.map = map;
            
            // DOM元素
            const apiKeyInput = document.getElementById('apiKey');
            const startPointInput = document.getElementById('startPoint');
            const endPointInput = document.getElementById('endPoint');
            const searchBtn = document.getElementById('searchBtn');
            const routeInfo = document.getElementById('routeInfo');
            const errorMsg = document.getElementById('errorMsg');
            const debugInfo = document.getElementById('debugInfo');

            const routePreference = document.getElementById('routePreference');
            const unitPriceInput = document.getElementById('unitPriceInput');
            const calcCostBtn = document.getElementById('calcCostBtn');
            const costInfo = document.getElementById('costInfo');
            
            // loading元素可能在某些情况下为null，需要在使用时检查
            function getLoadingElement() {
                return document.getElementById('loading');
            }
            
            // 存储起点/终点信息（坐标+地址）
            let start = { lng: null, lat: null, address: '' };
            let end = { lng: null, lat: null, address: '' };
            
            // 防抖函数
            function debounce(func, wait) {
                let timeout;
                return function executedFunction(...args) {
                    const later = () => {
                        clearTimeout(timeout);
                        func(...args);
                    };
                    clearTimeout(timeout);
                    timeout = setTimeout(later, wait);
                };
            }
            
            // 调试日志输出
            function logDebug(msg) {
                debugInfo.innerHTML += `<p>${new Date().toLocaleTimeString()}：${msg}</p>`;
                console.log("[调试] " + msg);
            }
            
            // 时间格式化函数（秒转为时分秒）
            function formatDuration(seconds) {
                // 确保输入是数字
                const sec = parseInt(seconds);
                if (isNaN(sec) || sec < 0) {
                    return '未知';
                }
                
                const hours = Math.floor(sec / 3600);
                const minutes = Math.floor((sec % 3600) / 60);
                const secs = sec % 60;
                
                if (hours > 0) {
                    return `${hours}小时${minutes}分钟${secs}秒`;
                } else if (minutes > 0) {
                    return `${minutes}分钟${secs}秒`;
                } else {
                    return `${secs}秒`;
                }
            }
            
            // 地址解析（带重试机制，确保获取坐标）
            function getPointFromAddress(address, city, retry = 0) {
                return new Promise((resolve, reject) => {
                    if (retry > 2) {
                        reject(new Error(`地址解析失败：${address}`));
                        return;
                    }
                        
                        // 使用高德地图地理编码服务
                        AMap.plugin('AMap.Geocoder', function() {
                            // 检查AMap.Geocoder是否存在
                            if (typeof AMap.Geocoder === 'undefined') {
                                reject(new Error("高德地图地理编码服务未正确加载"));
                                return;
                            }
                            
                            var geocoder = new AMap.Geocoder({
                                city: city || "全国"
                            });
                            
                            geocoder.getLocation(address, function(status, result) {
                                if (status === 'complete' && result.info === 'OK') {
                                    const geocode = result.geocodes[0];
                                    const location = geocode.location;
                                    logDebug(`解析成功：${address} → (${location.lng.toFixed(6)}, ${location.lat.toFixed(6)})`);
                                    resolve(location);
                                } else {
                                    logDebug(`解析失败（第${retry+1}次重试）：${address}`);
                                    setTimeout(() => {
                                        getPointFromAddress(address, city, retry + 1).then(resolve).catch(reject);
                                    }, 500);
                                }
                            });
                        });
                });
            }
                
            // 创建地址自动完成（输入提示）
            function createAutocomplete(inputId, isStart) {
                const input = document.getElementById(inputId);
                const suggestionBox = document.getElementById(isStart ? 'startSuggestion' : 'endSuggestion');
                
                // 使用高德地图输入提示插件（API 2.0版本使用AMap.AutoComplete）
                AMap.plugin('AMap.AutoComplete', function() {
                    try {
                        // 先检查AMap.AutoComplete是否存在
                        if (typeof AMap.AutoComplete === 'undefined') {
                            logDebug("自动完成插件未正确加载");
                            return;
                        }
                        
                        var autoOptions = {
                            city: '全国' // API 2.0推荐设置城市参数
                        };
                        var autocomplete = new AMap.AutoComplete(autoOptions);
                        
                        // 监听输入事件，提供搜索建议
                        input.addEventListener('input', function() {
                            const keyword = input.value.trim();
                            if (keyword.length > 0) {
                                // API 2.0使用search方法进行搜索
                                autocomplete.search(keyword, function(status, result) {
                                    if (status === 'complete' && result.info === 'OK') {
                                        suggestionBox.innerHTML = '';
                                        if (result.tips && result.tips.length > 0) {
                                            result.tips.slice(0, 10).forEach(tip => { // 限制显示10个建议
                                                const item = document.createElement('div');
                                                item.className = 'suggestion-item';
                                                
                                                // 创建名称元素
                                                const nameDiv = document.createElement('div');
                                                nameDiv.className = 'name';
                                                nameDiv.textContent = tip.name || '未知地点';
                                                
                                                // 创建地址元素
                                                const addressDiv = document.createElement('div');
                                                addressDiv.className = 'address';
                                                addressDiv.textContent = tip.district || tip.address || '';
                                                
                                                item.appendChild(nameDiv);
                                                if (addressDiv.textContent) {
                                                    item.appendChild(addressDiv);
                                                }
                                                item.onclick = async () => {
                                                    input.value = tip.name;
                                                    suggestionBox.style.display = 'none';
                                                    try {
                                                        // 使用tip的location信息或进行地址解析
                                                        let point;
                                                        if (tip.location) {
                                                            point = tip.location;
                                                        } else {
                                                            point = await getPointFromAddress(tip.name, tip.adcode);
                                                        }
                                                        if (isStart) {
                                                            start = { lng: point.lng, lat: point.lat, address: tip.name };
                                                        } else {
                                                            end = { lng: point.lng, lat: point.lat, address: tip.name };
                                                        }
                                                        errorMsg.textContent = "";
                                                        logDebug(`选择提示项成功：${tip.name} → (${point.lng.toFixed(6)}, ${point.lat.toFixed(6)})`);
                                                    } catch (err) {
                                                        logDebug("提示项解析失败：" + err.message);
                                                        errorMsg.textContent = `${isStart ? '起点' : '终点'}地址无效，请重新选择`;
                                                    }
                                                };
                                                suggestionBox.appendChild(item);
                                            });
                                            suggestionBox.style.display = 'block';
                                            logDebug(`搜索到${result.tips.length}个提示项`);
                                        } else {
                                            suggestionBox.style.display = 'none';
                                            logDebug("未找到匹配的提示项");
                                        }
                                    } else {
                                        suggestionBox.style.display = 'none';
                                        logDebug(`搜索失败：${status}, ${result ? result.info : '无结果'}`);
                                    }
                                });
                            } else {
                                suggestionBox.style.display = 'none';
                            }
                        });
                        
                        // 添加键盘导航支持
                        input.addEventListener('keydown', function(e) {
                            const items = suggestionBox.querySelectorAll('.suggestion-item');
                            if (items.length > 0) {
                                if (e.key === 'ArrowDown') {
                                    // 向下导航
                                    e.preventDefault();
                                    let currentIndex = -1;
                                    for (let i = 0; i < items.length; i++) {
                                        if (items[i].classList.contains('selected')) {
                                            currentIndex = i;
                                            items[i].classList.remove('selected');
                                            break;
                                        }
                                    }
                                    const nextIndex = (currentIndex + 1) % items.length;
                                    items[nextIndex].classList.add('selected');
                                } else if (e.key === 'ArrowUp') {
                                    // 向上导航
                                    e.preventDefault();
                                    let currentIndex = -1;
                                    for (let i = 0; i < items.length; i++) {
                                        if (items[i].classList.contains('selected')) {
                                            currentIndex = i;
                                            items[i].classList.remove('selected');
                                            break;
                                        }
                                    }
                                    const prevIndex = (currentIndex - 1 + items.length) % items.length;
                                    items[prevIndex].classList.add('selected');
                                } else if (e.key === 'Enter') {
                                    // 选择当前高亮项
                                    e.preventDefault();
                                    const selectedItem = suggestionBox.querySelector('.suggestion-item.selected');
                                    if (selectedItem) {
                                        selectedItem.click();
                                    }
                                } else if (e.key === 'Escape') {
                                    // ESC键关闭下拉框
                                    suggestionBox.style.display = 'none';
                                }
                            }
                        });
                        
                        // 输入框失焦时隐藏下拉框（延迟执行，以便点击下拉项时能正常工作）
                        input.addEventListener('blur', function() {
                            setTimeout(() => {
                                suggestionBox.style.display = 'none';
                            }, 200);
                        });
                        
                        // 输入框获得焦点时，如果有内容且有下拉项，则显示下拉框
                        input.addEventListener('focus', function() {
                            if (input.value.trim() && suggestionBox.children.length > 0) {
                                suggestionBox.style.display = 'block';
                            }
                        });
                        
                    } catch (error) {
                        logDebug("自动完成插件初始化失败：" + error.message);
                        console.error("自动完成插件初始化失败：", error);
                    }
                });
            }
            
            // 初始化自动完成
            AMap.plugin(['AMap.Autocomplete'], function() {
                // 确保DOM完全加载后再初始化
                setTimeout(() => {
                    try {
                        createAutocomplete("startPoint", true);
                        createAutocomplete("endPoint", false);
                        
                        // 添加全局点击事件，点击外部时关闭所有下拉框
                        document.addEventListener('click', function(e) {
                            const startSuggestion = document.getElementById('startSuggestion');
                            const endSuggestion = document.getElementById('endSuggestion');
                            const startInput = document.getElementById('startPoint');
                            const endInput = document.getElementById('endPoint');
                            
                            // 如果点击的不是输入框或下拉框，则关闭所有下拉框
                            if (!startInput.contains(e.target) && !startSuggestion.contains(e.target)) {
                                startSuggestion.style.display = 'none';
                            }
                            if (!endInput.contains(e.target) && !endSuggestion.contains(e.target)) {
                                endSuggestion.style.display = 'none';
                            }
                        });
                        
                        logDebug("自动完成插件初始化成功");
                    } catch (error) {
                        logDebug("自动完成插件初始化失败，将使用手动输入模式：" + error.message);
                        // 插件加载失败时的降级处理
                        setupManualInputMode();
                    }
                }, 100);
            }, function(error) {
                logDebug("自动完成插件加载失败，将使用手动输入模式：" + error);
                setupManualInputMode();
            });
            
            // 设置手动输入模式（当自动完成插件加载失败时的降级方案）
            function setupManualInputMode() {
                const startInput = document.getElementById('startPoint');
                const endInput = document.getElementById('endPoint');
                
                // 为输入框添加提示文本
                startInput.placeholder = "请输入起点地址，输入完成后点击其他地方或按Tab键进行解析";
                endInput.placeholder = "请输入终点地址，输入完成后点击其他地方或按Tab键进行解析";
                
                // 添加视觉提示
                startInput.style.borderColor = "#ffa500";
                endInput.style.borderColor = "#ffa500";
                
                logDebug("已启用手动输入模式，请在输入地址后失焦以触发解析");
            }
                
            // 手动输入地址解析
            async function handleManualAddress(input, isStart) {
                const address = input.value.trim();
                if (!address) {
                    isStart ? (start = { lng: null, lat: null, address: '' }) : (end = { lng: null, lat: null, address: '' });
                    return Promise.resolve();
                }
                    
                    // 显示解析中状态
                    const loadingElement = getLoadingElement();
                    if (loadingElement) {
                        loadingElement.textContent = `${isStart ? '起点' : '终点'}地址解析中，请稍候...`;
                        loadingElement.style.display = "block";
                    }
                    
                    try {
                        // 这里需要根据具体城市来解析，简化处理使用全国范围
                        const point = await getPointFromAddress(address);
                        if (isStart) {
                            start = { lng: point.lng, lat: point.lat, address };
                        } else {
                            end = { lng: point.lng, lat: point.lat, address };
                        }
                        logDebug(`手动解析${isStart ? '起点' : '终点'}成功`);
                        
                        // 隐藏解析中状态
                        if (loadingElement) {
                            loadingElement.style.display = "none";
                        }
                        
                        return Promise.resolve();
                    } catch (err) {
                        logDebug("手动解析失败：" + err.message);
                        errorMsg.textContent = `${isStart ? '起点' : '终点'}地址无法识别，请检查`;
                        
                        // 隐藏解析中状态
                        if (loadingElement) {
                            loadingElement.style.display = "none";
                        }
                        
                        return Promise.reject(err);
                    }
                }
                
                // 绑定手动输入事件
                startPointInput.addEventListener('blur', () => handleManualAddress(startPointInput, true));
                endPointInput.addEventListener('blur', () => handleManualAddress(endPointInput, false));
                
                // 添加输入事件监听，用于在自动完成插件失败时提供备用方案
                startPointInput.addEventListener('input', function() {
                    // 如果自动完成插件未加载，可以在这里添加其他处理逻辑
                    if (typeof AMap === 'undefined' || typeof AMap.Autocomplete === 'undefined') {
                        logDebug("自动完成插件未加载，使用手动输入模式");
                    }
                });
                
                endPointInput.addEventListener('input', function() {
                    // 如果自动完成插件未加载，可以在这里添加其他处理逻辑
                    if (typeof AMap === 'undefined' || typeof AMap.Autocomplete === 'undefined') {
                        logDebug("自动完成插件未加载，使用手动输入模式");
                    }
                });
                
                // 点击其他地方隐藏建议框
                document.addEventListener('click', function(e) {
                    if (!e.target.closest('.input-group')) {
                        document.getElementById('startSuggestion').style.display = 'none';
                        document.getElementById('endSuggestion').style.display = 'none';
                    }
                });
                
                // 在地图上显示路线
                function displayRouteOnMap(routeData, routeType) {
                    // 清除之前的路线和标记
                    if (window.startMarker) map.remove(window.startMarker);
                    if (window.endMarker) map.remove(window.endMarker);
                    if (window.routeLines) {
                        window.routeLines.forEach(line => map.remove(line));
                        window.routeLines = [];
                    }
                    
                    // 标记起点和终点
                    window.startMarker = new AMap.Marker({
                        position: [start.lng, start.lat],
                        title: '起点',
                        label: {
                            content: '起点',
                            offset: new AMap.Pixel(-10, -25)
                        }
                    });
                    
                    window.endMarker = new AMap.Marker({
                        position: [end.lng, end.lat],
                        title: '终点',
                        label: {
                            content: '终点',
                            offset: new AMap.Pixel(-10, -25)
                        }
                    });
                    
                    map.add([window.startMarker, window.endMarker]);
                    window.routeLines = []; // 初始化路线数组
                    
                    // 显示路线
                    if (routeData.route && routeData.route.paths && routeData.route.paths.length > 0) {
                        const path = routeData.route.paths[0];
                        
                        logDebug(`路径数据: ${JSON.stringify(path)}`);
                        
                        // 尝试使用路径级别的polyline（优先使用）
                        if (path.polyline) {
                            logDebug("使用路径级别的polyline");
                            try {
                                // 解析路径级别的polyline字符串
                                const pathArr = path.polyline.split(';');
                                logDebug(`路径polyline分割后长度: ${pathArr.length}`);
                                
                                // 检查分割后的数组是否为空
                                if (pathArr.length === 0 || (pathArr.length === 1 && pathArr[0] === "")) {
                                    logDebug("路径polyline分割后为空");
                                } else {
                                    const routePoints = pathArr.map(point => {
                                        const coords = point.split(',');
                                        if (coords.length >= 2) {
                                            const lng = parseFloat(coords[0]);
                                            const lat = parseFloat(coords[1]);
                                            return [lng, lat];
                                        }
                                        return null;
                                    }).filter(point => point !== null && !isNaN(point[0]) && !isNaN(point[1]));
                                    
                                    logDebug(`解析后的路径点数量: ${routePoints.length}`);
                                    
                                    if (routePoints.length > 0) {
                                        const routeLine = new AMap.Polyline({
                                            path: routePoints,
                                            strokeColor: "#38f",
                                            strokeWeight: 6,
                                            strokeOpacity: 0.8
                                        });
                                        
                                        map.add(routeLine);
                                        window.routeLines.push(routeLine);
                                        logDebug("成功绘制路径级别的路线");
                                    } else {
                                        logDebug("路径点数量为0，无法绘制路线");
                                    }
                                }
                            } catch (e) {
                                logDebug("Path polyline解析错误: " + e.message);
                                console.error("Path polyline解析错误:", e);
                            }
                        }
                        // 如果没有路径级别的polyline，尝试使用steps中的polyline
                        else if (path.steps) {
                            logDebug("使用步骤级别的polyline");
                            // 遍历所有步骤并绘制路线
                            path.steps.forEach((step, index) => {
                                // 高德地图驾驶路线V5接口使用的是polyline字段，但格式是分号分隔的坐标对
                                if (step.polyline) {
                                    try {
                                        // 解析polyline字符串
                                        const pathArr = step.polyline.split(';');
                                        logDebug(`步骤${index} polyline分割后长度: ${pathArr.length}`);
                                        
                                        // 检查分割后的数组是否为空
                                        if (pathArr.length === 0 || (pathArr.length === 1 && pathArr[0] === "")) {
                                            logDebug(`步骤${index} polyline分割后为空`);
                                        } else {
                                            const routePoints = pathArr.map(point => {
                                                const coords = point.split(',');
                                                if (coords.length >= 2) {
                                                    const lng = parseFloat(coords[0]);
                                                    const lat = parseFloat(coords[1]);
                                                    return [lng, lat];
                                                }
                                                return null;
                                            }).filter(point => point !== null && !isNaN(point[0]) && !isNaN(point[1]));
                                            
                                            logDebug(`步骤${index} 解析后的路径点数量: ${routePoints.length}`);
                                            
                                            if (routePoints.length > 0) {
                                                const routeLine = new AMap.Polyline({
                                                    path: routePoints,
                                                    strokeColor: "#38f",
                                                    strokeWeight: 6,
                                                    strokeOpacity: 0.8
                                                });
                                                
                                                map.add(routeLine);
                                                window.routeLines.push(routeLine);
                                                logDebug(`成功绘制步骤${index}的路线`);
                                            } else {
                                                logDebug(`步骤${index} 路径点数量为0，无法绘制路线`);
                                            }
                                        }
                                    } catch (e) {
                                        logDebug(`步骤${index} polyline解析错误: ` + e.message);
                                        console.error("Step polyline解析错误:", e);
                                    }
                                }
                            });
                            
                            // 如果steps中没有polyline，尝试连接各个步骤的起点和终点
                            if (window.routeLines.length === 0) {
                                logDebug("尝试连接各个步骤的起点和终点");
                                let routePoints = [];
                                path.steps.forEach((step, index) => {
                                    if (step.start_location) {
                                        const lng = parseFloat(step.start_location.lng);
                                        const lat = parseFloat(step.start_location.lat);
                                        if (!isNaN(lng) && !isNaN(lat)) {
                                            routePoints.push([lng, lat]);
                                        }
                                    }
                                    if (step.end_location) {
                                        const lng = parseFloat(step.end_location.lng);
                                        const lat = parseFloat(step.end_location.lat);
                                        if (!isNaN(lng) && !isNaN(lat)) {
                                            routePoints.push([lng, lat]);
                                        }
                                    }
                                });
                                
                                logDebug(`连接步骤后收集到的坐标点数量: ${routePoints.length}`);
                                
                                if (routePoints.length > 0) {
                                    const routeLine = new AMap.Polyline({
                                        path: routePoints,
                                        strokeColor: "#38f",
                                        strokeWeight: 6,
                                        strokeOpacity: 0.8
                                    });
                                    
                                    map.add(routeLine);
                                    window.routeLines.push(routeLine);
                                    logDebug("成功连接步骤绘制路线");
                                } else {
                                    logDebug("连接步骤后坐标点数量为0，无法绘制路线");
                                }
                            }
                        }
                        
                        // 如果仍然没有路线，使用备用方案（从步骤中提取坐标点）
                        if (window.routeLines.length === 0 && path.steps) {
                            logDebug("使用备用方案绘制路线");
                            // 使用steps中的坐标点构建路线
                            let routePoints = [];
                            path.steps.forEach((step, index) => {
                                // 检查是否有start_location和end_location
                                if (step.start_location) {
                                    const lng = parseFloat(step.start_location.lng);
                                    const lat = parseFloat(step.start_location.lat);
                                    if (!isNaN(lng) && !isNaN(lat)) {
                                        routePoints.push([lng, lat]);
                                    }
                                }
                                if (step.end_location) {
                                    const lng = parseFloat(step.end_location.lng);
                                    const lat = parseFloat(step.end_location.lat);
                                    if (!isNaN(lng) && !isNaN(lat)) {
                                        routePoints.push([lng, lat]);
                                    }
                                }
                                // 如果没有start_location和end_location，尝试使用其他坐标字段
                                else if (step.polyline) {
                                    // 从polyline中提取第一个和最后一个点作为起点和终点
                                    try {
                                        const pathArr = step.polyline.split(';');
                                        if (pathArr.length > 0) {
                                            const coords = pathArr[0].split(',');
                                            if (coords.length >= 2) {
                                                const lng = parseFloat(coords[0]);
                                                const lat = parseFloat(coords[1]);
                                                if (!isNaN(lng) && !isNaN(lat)) {
                                                    routePoints.push([lng, lat]);
                                                }
                                            }
                                        }
                                        if (pathArr.length > 1) {
                                            const coords = pathArr[pathArr.length - 1].split(',');
                                            if (coords.length >= 2) {
                                                const lng = parseFloat(coords[0]);
                                                const lat = parseFloat(coords[1]);
                                                if (!isNaN(lng) && !isNaN(lat)) {
                                                    routePoints.push([lng, lat]);
                                                }
                                            }
                                        }
                                    } catch (e) {
                                        logDebug(`步骤${index} polyline坐标提取错误: ` + e.message);
                                        console.error("Step polyline坐标提取错误:", e);
                                    }
                                }
                            });
                            
                            logDebug(`备用方案收集到的坐标点数量: ${routePoints.length}`);
                            
                            // 如果有坐标点，绘制路线
                            if (routePoints.length > 0) {
                                const routeLine = new AMap.Polyline({
                                    path: routePoints,
                                    strokeColor: "#38f",
                                    strokeWeight: 6,
                                    strokeOpacity: 0.8
                                });
                                
                                map.add(routeLine);
                                window.routeLines.push(routeLine);
                                logDebug("成功使用备用方案绘制路线");
                            } else {
                                logDebug("备用方案坐标点数量为0，无法绘制路线");
                            }
                        }
                        
                        logDebug(`总共绘制的路线数量: ${window.routeLines.length}`);
                        
                        // 调整地图视野以适应路线
                        const allOverlays = [window.startMarker, window.endMarker];
                        if (window.routeLines.length > 0) {
                            allOverlays.push(...window.routeLines);
                        }
                        map.setFitView(allOverlays.filter(overlay => overlay !== undefined));
                        logDebug("地图视野调整完成");
                    }
                }
                
                // 显示路线信息
                function displayRouteInfo(routeData, routeType) {
                    if (!routeData.route || !routeData.route.paths || routeData.route.paths.length === 0) {
                        errorMsg.textContent = "未找到有效路线信息";
                        return;
                    }
                    
                    const path = routeData.route.paths[0];
                    
                    // 路线总长度（米转公里）
                    const distance = path.distance ? (parseFloat(path.distance) / 1000).toFixed(1) : '未知';
                    
                    // 预计耗时（优先使用cost.cost.duration，否则使用path.cost.duration）
                    let duration = '未知';
                    if (path.cost.duration !== undefined) {
                        duration = formatDuration(parseInt(path.cost.duration));
                    }
                    
                    // 道路收费信息（v5接口从cost对象获取）
                    let toll = '未知';
                    if (path.cost && path.cost.tolls !== undefined) {
                        toll = path.cost.tolls;
                    } else if (path.tolls !== undefined) {
                        toll = path.tolls;
                    }
                    
                    // 收费路段里程（米转公里，v5接口从cost对象获取）
                    let tollDistance = '未知';
                    if (path.cost && path.cost.toll_distance !== undefined) {
                        tollDistance = (parseFloat(path.cost.toll_distance) / 1000).toFixed(1);
                    } else if (path.toll_distance !== undefined) {
                        tollDistance = (parseFloat(path.toll_distance) / 1000).toFixed(1);
                    }
                    
                    // 红绿灯数量（v5接口从cost对象获取）
                    let trafficLight = '未知';
                    if (path.cost && path.cost.traffic_lights !== undefined) {
                        trafficLight = path.cost.traffic_lights;
                    } else if (path.traffic_lights !== undefined) {
                        trafficLight = path.traffic_lights;
                    }
                    
                    // 构建路线步骤HTML
                    let stepsHtml = '<ol class="route-detail">';
                    let totalSteps = 0;
                    
                    if (path.steps) {
                        totalSteps = path.steps.length;
                        path.steps.forEach((step, index) => {
                            // 获取路线步骤信息
                            const instruction = step.instruction || '';
                            const roadName = step.road_name || '';
                            
                            // 步骤距离（米转公里）
                            let stepDistance = '';
                            if (step.step_distance !== undefined) {
                                stepDistance = `(${(parseFloat(step.step_distance) / 1000).toFixed(1)}公里)`;
                            } else if (step.distance !== undefined) {
                                stepDistance = `(${(parseFloat(step.distance) / 1000).toFixed(1)}公里)`;
                            }
                            
                            // 步骤耗时
                            let stepDuration = '';
                            if (step.duration !== undefined) {
                                stepDuration = ` [${formatDuration(parseInt(step.duration))}]`;
                            }
                            
                            // 步骤收费信息（v5接口）
                            let stepToll = '';
                            if (step.cost && step.cost.tolls !== undefined && parseFloat(step.cost.tolls) > 0) {
                                stepToll = ` 💰${step.cost.tolls}元`;
                            }
                            
                            // 步骤红绿灯信息（v5接口）
                            let stepTrafficLights = '';
                            if (step.traffic_lights !== undefined && parseInt(step.traffic_lights) > 0) {
                                stepTrafficLights = ` 🚦${step.traffic_lights}个`;
                            }
                            
                            // 组合显示信息
                            let stepInfo = instruction || roadName || '未知路段';
                            if (stepDistance && !stepInfo.includes('公里')) {
                                stepInfo += ' ' + stepDistance;
                            }
                            stepInfo += stepDuration + stepToll + stepTrafficLights;
                            
                            stepsHtml += `<li>${stepInfo}</li>`;
                        });
                    }
                    
                    stepsHtml += '</ol>';
                    
                    // 显示结果
                    routeInfo.innerHTML = `
                        <p><strong>起点：</strong>${start.address}</p>
                        <p><strong>终点：</strong>${end.address}</p>
                        <p><strong>地图类型：</strong>高德地图</p>
                        <p><strong>路线长度：</strong>${distance} 公里</p>
                        <p><strong>预计耗时：</strong>${duration}</p>
                        <p><strong>道路收费：</strong>${toll} 元</p>
                        <p><strong>收费路段里程：</strong>${tollDistance} 公里</p>
                        <p><strong>红绿灯数量：</strong>${trafficLight} 个</p>
                        <p><strong>路线步骤（共${totalSteps}步）：</strong></p>
                        ${stepsHtml}
                    `;

                    // 保存最新路线长度（公里），用于费用计算
                    const distNum = parseFloat(distance);
                    window.latestRouteDistanceKM = isNaN(distNum) ? undefined : distNum;
                    if (costInfo) {
                        costInfo.innerHTML = "";
                    }
                    
                    logDebug(`路线显示成功：${distance}公里，${totalSteps}个步骤`);
                }
                
                // 核心：路线规划函数
                async function planRoute() {
                    // 防止重复点击
                    if (searchBtn.disabled) {
                        return;
                    }
                    
                    // 重置状态
                    errorMsg.textContent = "";
                    routeInfo.innerHTML = "";
                    debugInfo.innerHTML = "调试信息：";
                    
                    // 清除之前的路线和标记
                    if (window.startMarker) map.remove(window.startMarker);
                    if (window.endMarker) map.remove(window.endMarker);
                    if (window.routeLines) {
                        window.routeLines.forEach(line => map.remove(line));
                        window.routeLines = [];
                    }
                    
                    // 验证API Key
                    const apiKey = apiKeyInput.value.trim();
                    if (!apiKey) {
                        errorMsg.textContent = "请先输入高德地图API Key";
                        apiKeyInput.focus();
                        return;
                    }
                    
                    // 检查起点输入并触发解析
                    if (startPointInput.value.trim() && (!start.lng || !start.lat)) {
                        try {
                            await handleManualAddress(startPointInput, true);
                        } catch (err) {
                            errorMsg.textContent = "起点地址解析失败，请检查后重试";
                            return;
                        }
                    }
                    
                    // 检查终点输入并触发解析
                    if (endPointInput.value.trim() && (!end.lng || !end.lat)) {
                        try {
                            await handleManualAddress(endPointInput, false);
                        } catch (err) {
                            errorMsg.textContent = "终点地址解析失败，请检查后重试";
                            return;
                        }
                    }
                    
                    // 验证起点终点
                    if (!start.lng || !start.lat) {
                        errorMsg.textContent = "请先选择有效的起点（输入地址后请确保已选择或确认）";
                        startPointInput.focus();
                        return;
                    }
                    if (!end.lng || !end.lat) {
                        errorMsg.textContent = "请先选择有效的终点（输入地址后请确保已选择或确认）";
                        endPointInput.focus();
                        return;
                    }
                    if (start.lng === end.lng && start.lat === end.lat) {
                        errorMsg.textContent = "起点和终点不能相同";
                        return;
                    }
                    
                    // 获取路线偏好选项
                    const routeTacticsValue = routePreference.value;
                    
                    // 显示加载状态
                    const loadingElement = getLoadingElement();
                    if (loadingElement) {
                        loadingElement.textContent = "正在规划路线，请稍候...";
                        loadingElement.style.display = "block";
                    }
                    searchBtn.disabled = true;
                    logDebug("开始规划路线...");
                    
                    // 准备请求数据
                    const requestData = {
                        origin: `${start.lat},${start.lng}`,
                        destination: `${end.lat},${end.lng}`,
                        route_type: "driving",  // 默认为驾车路线
                        tactics: routeTacticsValue,
                        ak: apiKey
                    };
                    
                    logDebug(`请求数据：${JSON.stringify(requestData)}`);
                    
                    // 调用后端接口获取路线信息
                    fetch('/api/map/sdk/gaode/mapSdkGaode/noGetwayReadRoute', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify(requestData)
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }
                        return response.json();
                    })
                    .then(data => {
                        // 隐藏加载状态
                        if (loadingElement) {
                            loadingElement.style.display = "none";
                        }
                        searchBtn.disabled = false;
                        
                        logDebug(`接收到的响应数据: ${JSON.stringify(data)}`);
                        
                        if (data.code === 0) {
                            // 处理成功响应
                            const routeData = data.data;
                            
                            // 显示路线在地图上
                            displayRouteOnMap(routeData, "driving");
                            
                            // 显示路线信息
                            displayRouteInfo(routeData, "driving");
                        } else {
                            // 处理错误响应
                            errorMsg.textContent = `路线规划失败：${data.msg}`;
                            logDebug(`路线规划失败：${data.msg}`);
                        }
                    })
                    .catch(error => {
                        // 隐藏加载状态
                        if (loadingElement) {
                            loadingElement.style.display = "none";
                        }
                        searchBtn.disabled = false;
                        
                        errorMsg.textContent = `请求失败：${error.message}`;
                        logDebug(`请求失败：${error.message}`);
                        console.error("请求失败:", error);
                    });
                }
                
                // 创建防抖版本的函数
                const debouncedPlanRoute = debounce(planRoute, 300);
                const debouncedCalculateCost = debounce(calculateCost, 300);
                
                // 绑定查询事件（使用防抖）
                searchBtn.addEventListener('click', debouncedPlanRoute);
                
                // 路线偏好变化时自动查询路线
                if (routePreference) {
                    routePreference.addEventListener('change', function() {
                        // 只有在起点和终点都已设置的情况下才自动查询
                        if (start.lng && start.lat && end.lng && end.lat) {
                            logDebug(`路线偏好已更改为：${this.options[this.selectedIndex].text}，自动重新规划路线`);
                            debouncedPlanRoute();
                        }
                    });
                }

                // 计算费用：调用后端费用计算接口
                function calculateCost() {
                    const distanceKM = window.latestRouteDistanceKM;
                    if (distanceKM === undefined) {
                        errorMsg.textContent = "请先查询路线以获取路线长度";
                        return;
                    }
                    const unitPriceVal = parseFloat(unitPriceInput ? unitPriceInput.value : "");
                    if (isNaN(unitPriceVal) || unitPriceVal <= 0) {
                        errorMsg.textContent = "请输入有效的里程单价（元/公里）";
                        if (unitPriceInput) unitPriceInput.focus();
                        return;
                    }
                    errorMsg.textContent = "";
                    if (costInfo) costInfo.innerHTML = "正在计算费用...";

                    fetch('/api/map/cost/mapCost/noGetwayReadCost', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            distance: distanceKM,
                            unitPrice: unitPriceVal
                        })
                    })
                    .then(res => res.json())
                    .then(data => {
                        if (data.code === 0 && data.data) {
                            const result = data.data;
                            if (costInfo) {
                                costInfo.innerHTML = `
                                    <p><strong>费用计算：</strong>${result.distance} 公里 × ${result.unitPrice} 元/公里 = <strong>${result.cost} 元</strong></p>
                                `;
                            }
                            logDebug(`费用计算成功：${result.cost}元`);
                        } else {
                            const msg = data.msg || "费用计算失败";
                            if (costInfo) costInfo.innerHTML = `<p style="color:#f00;">${msg}</p>`;
                            logDebug(`费用计算失败：${msg}`);
                        }
                    })
                    .catch(err => {
                        if (costInfo) costInfo.innerHTML = `<p style=\"color:#f00;\">请求失败：${err.message}</p>`;
                        logDebug(`费用计算异常：${err.message}`);
                    });
                }

                if (calcCostBtn) {
                    calcCostBtn.addEventListener('click', debouncedCalculateCost);
                }
                
                // Enter键触发查询（使用防抖）
                [startPointInput, endPointInput].forEach(input => {
                    input.addEventListener('keypress', (e) => {
                        if (e.key === 'Enter') {
                            debouncedPlanRoute();
                        }
                    });
                });

                // 页面加载检查
                window.addEventListener('load', () => {
                    if (typeof AMap === 'undefined') {
                        errorMsg.textContent = "高德地图API加载失败，请检查网络或AK";
                        logDebug("API加载失败：未找到AMap对象");
                    } else {
                        logDebug("高德地图API加载成功，可开始使用");
                    }
                });
            });

    </script>
</body>
</html>